package ca.camosun.proximity;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.widget.Toast;

public class BluetoothScan extends Activity {
	
	Room theRoom = Room.getInstance();
	
	BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter();
	{
		int REQUEST_ENABLE_BT = 1;

		if (bluetooth == null) {
			String nsup;
			nsup = "Device does not support bluetooth T_T";
			Toast.makeText(this, nsup, Toast.LENGTH_LONG).show();
		}

		if (bluetooth.isEnabled()) {
			String status;

			Intent enableBtIntent = new Intent(
					BluetoothAdapter.ACTION_REQUEST_ENABLE);
			startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);

			String mydeviceaddress = bluetooth.getAddress();
			String mydevicename = bluetooth.getName();
			status = mydevicename + " : " + mydeviceaddress;

			Toast.makeText(this, status, Toast.LENGTH_LONG).show();
		}	
		
		Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
				discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 0);
				startActivity(discoverableIntent);
		
		// Create a BroadcastReceiver for ACTION_FOUND
		final BroadcastReceiver mReceiver = new BroadcastReceiver() {
		    public void onReceive(Context context, Intent intent) {
		        String action = intent.getAction();
		        String name = null;
		        String address = null;
		        
		        SavedPerson found = new SavedPerson(name,address);
		        
		        // When discovery finds a device
		        if (BluetoothDevice.ACTION_FOUND.equals(action)) {
		            // Get the BluetoothDevice object from the Intent
		            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
		            /* Add the name and address to an array adapter to show in a ListView
		            mArrayAdapter.add(device.getName() + "\n" + device.getAddress());*/
		            
		            name = device.getName();
		            address = device.getAddress();
		            
		            found.setName(name);
		            found.setAddress(address);
		            theRoom.foundADevice(found);
		        }
		    }
		};
		// Register the BroadcastReceiver
		IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
		registerReceiver(mReceiver, filter); // Don't forget to unregister during onDestroy

	}
}
